//
//  NavigationController.swift
//  FuXingApp
//
//  Created by hungraim on 2021/7/28.
//

import UIKit

public typealias SSCallBack = ()->()

class NavigationController: UINavigationController {
    
    var callBack: SSCallBack?     // 闭包
    override func viewDidLoad() {
        super.viewDidLoad()
        
        interactivePopGestureRecognizer?.delegate = self
    }
    
    // 重写这两个方法 修复 控制 preferredStatusBarStyle 方法无效
    override var childForStatusBarHidden: UIViewController? {
        return self.topViewController
    }

    override var childForStatusBarStyle: UIViewController? {
        return self.topViewController
    }
    
    
    override func pushViewController(_ viewController: UIViewController, animated: Bool) {
//        if (children.count > 0 || viewController.isKind(of: SSPhoneLoginViewController.self)) { //不是根控制器
        if (children.count > 0) {
            //隐藏tabBar
            viewController.hidesBottomBarWhenPushed = true
            
//            设置返回按钮
            let backImg = UIImage(named: "icon_nav_back")
            let leftItem = UIBarButtonItem(image: backImg, style: .plain, target: self, action: #selector(back))
            viewController.navigationItem.leftBarButtonItem = leftItem
        }
        
        
        
        super.pushViewController(viewController, animated: animated)
    }
    func callback(_ finished: @escaping SSCallBack) {
        callBack = finished
    }
}


// MARK: - 事件
extension NavigationController {
    @objc fileprivate func back() {
        
//        debugPrint("---1\(children.first)")
//        
//        if presentingViewController != nil {
//            debugPrint("---2\(presentingViewController)")
//        }
//        
//        if presentingViewController != nil {
//            debugPrint("---2\(presentedViewController)")
//        }
        
        if (children.first?.isKind(of: SSPhoneLoginViewController.self))! && presentingViewController != nil {
            dismiss(animated: true, completion: nil)
        } else {
            popViewController(animated: true)
        }
        (callBack ?? {})()
    }
}

// MARK: - UIGestureRecognizerDelegate
extension NavigationController: UIGestureRecognizerDelegate {
    // 接收到多个手势的代理方法
    func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
        // 判断是否是侧滑相关手势
        if gestureRecognizer == interactivePopGestureRecognizer && gestureRecognizer.isKind(of: UIPanGestureRecognizer.self) {
            let pan = gestureRecognizer as! UIPanGestureRecognizer
            let point = pan.translation(in: view)
            // 如果是侧滑相关的手势，并且手势的方向是侧滑的方向就让多个手势共存
            if point.x > 0 {
                return true
            }
        }
        return false
    }
}
